<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>基本列表</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <input type="text" placeholder="搜索" v-model="keyword">
        <button @click="sortType=2">年龄升序</button>
        <button @click="sortType=1">年龄降序</button>
        <button @click="sortType=0">原顺序</button>
        <ul>
            <li v-for="(p ,index) in filterPersons" :key="p.id">
                {{p.name}}-{{p.des}}-{{p.sex}}
            </li>
        </ul>
    </div>
</body>
<!--   JS   -->
    <script>
        //用watch实现
        /* new Vue({
            el:'#root',
            data:{
                keyword:'',
                persons:[
                    {id:'001',name:'马冬梅',des:'1',sex:'女'},
                    {id:'002',name:'周冬雨',des:'2',sex:'女'},
                    {id:'003',name:'周杰伦',des:'3',sex:'男'},
                    {id:'004',name:'汪伦',des:'4',sex:'男'}
                ],
                filterPersons:[]
            },
            watch:{
                keyword(val){
                    console.log('keyword改变',val),
                    this.filterPersons = this.persons.filter((p)=>{//filter过滤后是生成新的数组
                        return p.name.indexOf(val)!==-1
                    })
                },
                keyword:{
                    immediate:true,
                    handler(val){
                        this.filterPersons = this.persons.filter((p)=>{//filter过滤后是生成新的数组
                        return p.name.indexOf(val)!==-1
                    })
                    }
                }
            }
        }) */
        
        //用computed实现
        new Vue({
            el:'#root',
            data:{
                keyword:'',
                sortType:0,//0原顺序1降序2升序
                persons:[
                    {id:'001',name:'马冬梅',des:18,sex:'女'},
                    {id:'002',name:'周冬雨',des:26,sex:'女'},
                    {id:'003',name:'周杰伦',des:48,sex:'男'},
                    {id:'004',name:'汪伦',des:35,sex:'男'}
                ],
            },
            computed:{
                filterPersons(){
                    const arr =  this.persons.filter((p)=>{//filter过滤后是生成新的数组
                        return p.name.indexOf(this.keyword)!==-1
                        
                    })
                    //判断是否需要排序
                    if(this.sortType){
                        arr.sort((p1,p2)=>{
                            return this.sortType ===1 ? p2.des-p1.des : p1.des-p2.des
                            
                        })
                    }
                    return arr
                }
            }
        })
    </script>
</html>